import * as XLSX from 'xlsx';
import { Document, Packer, Paragraph, TextRun } from 'docx';
import { saveAs } from 'file-saver';
import JSZip from 'jszip';

// 文档处理工具类
export class DocumentUtils {
  // 判断文件是否为标准 docx（zip 格式）
  static async isRealDocx(file) {
    // file: File 或 Blob
    try {
      const arrayBuffer = await file.arrayBuffer();
      const zip = await JSZip.loadAsync(arrayBuffer);
      // docx 必须包含 word/document.xml
      return zip.file('word/document.xml') !== null;
    } catch (e) {
      return false;
    }
  }
  // Excel文件处理
  static async processExcelFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const sheetNames = workbook.SheetNames;
          const sheets = {};
          const merges = {};
          sheetNames.forEach(sheetName => {
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, blankrows: false });
            const maxCol = jsonData.reduce((max, row) => Math.max(max, row.length), 0);
            const paddedData = jsonData.map(row => {
              const newRow = [...row];
              while (newRow.length < maxCol) newRow.push('');
              return newRow;
            });
            sheets[sheetName] = paddedData;
            // 解析合并单元格
            if (worksheet['!merges']) {
              merges[sheetName] = worksheet['!merges'].map(m => ({
                row: m.s.r,
                col: m.s.c,
                rowspan: m.e.r - m.s.r + 1,
                colspan: m.e.c - m.s.c + 1
              }));
            } else {
              merges[sheetName] = [];
            }
          });
          resolve({
            type: 'excel',
            sheets,
            merges,
            sheetNames,
            originalFile: file
          });
        } catch (error) {
          reject(error);
        }
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  }

  // Word文档处理
  // utils/documentUtils.js
  static async processWordFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const zip = new JSZip();
          const zipContent = await zip.loadAsync(e.target.result);
          const documentXml = await zipContent.file('word/document.xml').async('string');
          const documentXmlParser = new DOMParser();
          const xmlDoc = documentXmlParser.parseFromString(documentXml, 'text/xml');
          // 遍历段落
          const paragraphs = Array.from(xmlDoc.getElementsByTagName('w:p')).map(p => {
            let text = '';
            // 拼接段落内所有文本
            p.querySelectorAll('w\\:t, t').forEach(t => {
              text += t.textContent;
            });
            // 处理换行
            p.querySelectorAll('w\\:br, br').forEach(() => {
              text += '\n';
            });
            return text;
          });
          resolve({
            type: 'word',
            paragraphs,
            originalFile: file
          });
        } catch (error) {
          reject(error);
        }
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  }

  // 生成Excel文件
  static async generateExcelFile(data, filename = 'document.xlsx') {
    const workbook = XLSX.utils.book_new();

    if (Array.isArray(data)) {
      // 如果是数组，创建单个工作表
      const worksheet = XLSX.utils.aoa_to_sheet(data);
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    } else if (typeof data === 'object') {
      // 如果是对象，可能包含多个工作表
      Object.keys(data).forEach(sheetName => {
        const worksheet = XLSX.utils.aoa_to_sheet(data[sheetName]);
        XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
      });
    }

    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    saveAs(blob, filename);
  }

  // 生成Word文档
  static async generateWordFile(content, filename = 'document.docx') {
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: content,
                size: 24,
              }),
            ],
          }),
        ],
      }],
    });

    const blob = await Packer.toBlob(doc);
    saveAs(blob, filename);
  }

  // 获取文件类型
  static getFileType(filename) {
    const extension = filename.split('.').pop().toLowerCase();
    const typeMap = {
      'xlsx': 'excel',
      'xls': 'excel',
      'docx': 'word',
      'doc': 'word',
      'jpg': 'image',
      'jpeg': 'image',
      'png': 'image',
      'gif': 'image',
      'bmp': 'image',
      'pdf': 'pdf'
    };
    return typeMap[extension] || 'unknown';
  }

  // 检查文件是否可预览
  static isPreviewable(filename) {
    const fileType = this.getFileType(filename);
    return ['excel', 'word', 'image', 'pdf'].includes(fileType);
  }

  // 检查文件是否可编辑
  static isEditable(filename) {
    const fileType = this.getFileType(filename);
    return ['excel', 'word'].includes(fileType);
  }
}

// 文件预览工具
export class FilePreviewUtils {
  // 获取文件预览URL
  static getPreviewUrl(fileUrl, baseUrl = 'http://localhost:3000') {
    if (!fileUrl) return null;

    // 如果已经是完整URL，直接返回
    if (fileUrl.startsWith('http')) {
      return fileUrl;
    }

    // 否则拼接基础URL
    return `${baseUrl}${fileUrl}`;
  }

  // 获取文件下载URL
  static getDownloadUrl(fileUrl, baseUrl = 'http://localhost:3000') {
    return this.getPreviewUrl(fileUrl, baseUrl);
  }
}